<template>
  <div class="app-container">
    <div class="tree-container">
      <!-- 操作区域 -->
      <div class="tree-header">
        <div class="header-title">
          <i class="el-icon-s-grid"></i>
          <span>美团类目管理</span>
        </div>
        <div class="header-actions">
          <el-button 
            type="primary" 
            class="action-btn add-btn" 
            icon="el-icon-plus" 
            size="mini" 
            @click="handleAdd()"
          >新增根类目</el-button>

          <el-button 
            type="info" 
            class="action-btn toggle-btn" 
            icon="el-icon-sort" 
            size="mini" 
            @click="toggleExpandAll"
          >展开/折叠</el-button>
          
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="tree-content">
        <el-table
          v-loading="loading"
          :data="treeList"
          row-key="id"
          lazy
          :load="loadChildren"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :border="true"
          :header-cell-style="headerCellStyle"
          :row-class-name="setTreeRowClass"
          width="100%"
          class="tree-table"
          ref="treeTable"
        >
          <el-table-column label="美团类目ID" min-width="160">
            <template slot-scope="scope">
              <div class="id-cell">
                <span class="id-badge">{{ scope.row.categoryId }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="美团类目名" align="center" min-width="220">
            <template slot-scope="scope">
              <div class="name-cell">
                <i :class="getLevelIcon(scope.row)"></i>
                <span class="name-text">{{ scope.row.name }}</span>
                <el-tag size="mini" :type="getLevelTagType(scope.row)" class="level-tag">
                  {{ getLevelText(scope.row) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="父ID" align="center" width="180">
            <template slot-scope="scope">
              <div class="parent-cell">
                <template v-if="scope.row.parentId > 0">
                  <i class="el-icon-top parent-icon"></i>
                  <span class="parent-id">{{ scope.row.parentId }}</span>
                </template>
                <template v-else>
                  <span class="root-node">根节点</span>
                </template>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="层级" align="center" width="120">
            <template slot-scope="scope">
              <div class="level-cell">
                <el-progress 
                  :percentage="scope.row.level * 33" 
                  :stroke-width="10" 
                  :show-text="false"
                  :color="getLevelColor(scope.row)"
                ></el-progress>
                <span class="level-value">{{ scope.row.level }}</span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="关联属性" align="center" width="120">
            <template slot-scope="scope">
              <div class="attr-cell">
                <el-button 
                  v-if="scope.row.level === 3" 
                  type="success" 
                  size="mini" 
                  class="attr-indicator" 
                  icon="el-icon-connection"
                  @click="handleConfig(scope.row)"
                >配置</el-button>
                <span v-else class="no-attr">
                  <i class="el-icon-close"></i>
                  不可配置
                </span>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" align="center" width="220">
            <template slot-scope="scope">
              <div class="operation-btns">
                <el-tooltip content="编辑类目" placement="top">
                  <el-button 
                    type="primary" 
                    icon="el-icon-edit" 
                    circle
                    size="mini" 
                    class="op-btn edit-btn" 
                    @click="handleUpdate(scope.row)"
                  ></el-button>
                </el-tooltip>
                
                <el-tooltip content="添加子类目" placement="top">
                  <el-button 
                    type="success" 
                    icon="el-icon-plus" 
                    circle
                    size="mini" 
                    class="op-btn add-btn" 
                    @click="handleAdd(scope.row)"
                  ></el-button>
                </el-tooltip>
                
                <el-tooltip content="删除类目" placement="top">
                  <el-button 
                    type="danger" 
                    icon="el-icon-delete" 
                    circle
                    size="mini" 
                    class="op-btn delete-btn" 
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
                
                <el-tooltip v-if="scope.row.level === 3" content="配置属性" placement="top">
                  <el-button 
                    type="warning"
                    icon="el-icon-setting" 
                    circle
                    size="mini" 
                    class="op-btn config-btn" 
                    @click="handleConfig(scope.row)"
                  ></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加或修改美团类目对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="550px" 
      append-to-body
      class="tree-dialog"
    >
      <div class="dialog-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="美团类目ID" prop="categoryId">
            <el-input 
              v-model="form.categoryId" 
              placeholder="请输入美团类目ID" 
              class="custom-input"
              prefix-icon="el-icon-key"
            />
          </el-form-item>
          
          <el-form-item label="美团类目名" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入美团类目名" 
              class="custom-input"
              prefix-icon="el-icon-document"
            />
          </el-form-item>
          
          <el-form-item label="父级类目" prop="parentId">
            <div class="parent-selector">
              <treeselect 
                v-model="form.parentId" 
                :options="treeOptions" 
                :normalizer="normalizer" 
                placeholder="请选择父级类目" 
                class="custom-select"
              />
              <div v-if="form.parentId" class="parent-info">
                <i class="el-icon-info"></i>
                <span>当前选择的父级ID: {{form.parentId}}</span>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item label="层级" prop="level">
            <el-input-number 
              v-model="form.level" 
              :min="1" 
              :max="3" 
              :step="1"
              placeholder="请输入层级"
              class="custom-number"
            />
            <div class="level-hint">
              <i class="el-icon-info"></i>
              <span>类目层级影响数据结构和配置选项</span>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-check" @click="submitForm">确 定</el-button>
        <el-button icon="el-icon-close" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 配置对话框 -->
    <el-dialog 
      :title="'配置属性 - ' + configForm.name" 
      :visible.sync="configOpen" 
      width="650px" 
      append-to-body
      class="config-dialog"
    >
      <div class="config-content">
        <div class="config-info">
          <div class="info-item">
            <span class="info-label"><i class="el-icon-document"></i> 类目名称:</span>
            <span class="info-value">{{ configForm.name }}</span>
          </div>
          <div class="info-item">
            <span class="info-label"><i class="el-icon-key"></i> 类目ID:</span>
            <span class="info-value">{{ configForm.categoryId }}</span>
          </div>
        </div>
        
        <el-divider content-position="center">属性配置</el-divider>
        
        <el-form ref="configForm" :model="configForm" label-width="100px">
          <el-form-item label="属性列表">
            <div class="attribute-selector">
              <el-select
                v-model="configForm.selectedAttributes"
                multiple
                filterable
                clearable
                placeholder="请选择属性"
                style="width: 100%"
                class="custom-select"
              >
                <el-option
                  v-for="item in attributeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <div class="attribute-option">
                    <i class="el-icon-price-tag"></i>
                    <span>{{ item.name }}</span>
                  </div>
                </el-option>
              </el-select>
              
              <div class="selected-count">
                <i class="el-icon-collection-tag"></i>
                <span>已选择 {{ configForm.selectedAttributes.length }} 个属性</span>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-check" @click="submitConfigForm">保存配置</el-button>
        <el-button icon="el-icon-close" @click="configOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTree, getTree, delTree, addTree, updateTree, addAttribute, getAttribute } from '@/api/business/tree';
import { listAttribute } from '@/api/business/attribute';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import Treeselect from '@riophae/vue-treeselect';

export default {
  name: 'Tree',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 美团类目表格树数据
      treeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        categoryId: null,
        name: null,
        parentId: 0,
        level: null
      },
      // 表单参数
      form: {
        id: null,
        categoryId: '',
        name: '',
        parentId: null,
        level: null
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '美团类目名不能为空', trigger: 'blur' }],
        categoryId: [{ required: true, message: '美团类目ID不能为空', trigger: 'blur' }]
      },
      // 树选择配置项
      treeOptions: [],
      // 树选择项格式化
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      // 配置对话框显示状态
      configOpen: false,
      // 配置表单数据
      configForm: {
        id: null,
        name: '',
        categoryId: '',
        selectedAttributes: []
      },
      attributeOptions: [],
      cascaderProps: {
        value: 'value',
        label: 'label',
        children: 'children',
        multiple: true
      }
    }
  },
  created() {
    this.getList();
    // 获取属性列表
    this.loadAttributes();
  },
  methods: {
    /** 表格头部样式 */
    headerCellStyle() {
      return {
        background: 'linear-gradient(to right, #f0f5ff, #e6f7ff)',
        color: '#3a5a97',
        fontWeight: '600',
        padding: '12px 0'
      }
    },
    
    /** 设置行样式 */
    setTreeRowClass({ row }) {
      return `tree-row level-${row.level}`;
    },
    
    /** 获取层级图标 */
    getLevelIcon(row) {
      const icons = {
        1: 'el-icon-s-grid',
        2: 'el-icon-s-unfold',
        3: 'el-icon-s-help'
      };
      return icons[row.level] || 'el-icon-s-operation';
    },
    
    /** 获取层级标签类型 */
    getLevelTagType(row) {
      const types = {
        1: '',
        2: 'success',
        3: 'warning'
      };
      return types[row.level] || 'info';
    },
    
    /** 获取层级文本 */
    getLevelText(row) {
      const texts = {
        1: '一级类目',
        2: '二级类目',
        3: '三级类目'
      };
      return texts[row.level] || `${row.level}级类目`;
    },
    
    /** 获取层级颜色 */
    getLevelColor(row) {
      const colors = {
        1: '#67C23A',
        2: '#409EFF',
        3: '#E6A23C'
      };
      return colors[row.level] || '#909399';
    },
    
    /** 查询美团类目列表 */
    getList() {
      this.loading = true;
      listTree({ parentId: 0 }).then(response => {
        this.treeList = response.data.map(item => ({
          ...item,
          hasChildren: item.level < 3 // 如果层级小于3，则表示还有子节点
        }));
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        categoryId: null,
        name: null,
        parentId: 0,
        level: null
      };
      this.handleQuery();
    },

    // 配置类目属性
    handleRouteJump() {
      this.$router.push({ path: '/business/attributes' });
    },

    loadChildren(tree, treeNode, resolve) {
      listTree({ parentId: tree.id }).then(response => {
        const children = response.data.map(item => ({
          ...item,
          hasChildren: item.level < 3 // 如果层级小于3，则表示还有子节点
        }));
        resolve(children);
      }).catch(() => {
        resolve([]);
      });
    },

    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.treeList.forEach(row => {
          this.$refs.treeTable.toggleRowExpansion(row, this.isExpandAll);
          if (row.children) {
            row.children.forEach(child => {
              this.$refs.treeTable.toggleRowExpansion(child, this.isExpandAll);
            });
          }
        });
      });
    },

    handleAdd(row) {
      this.resetForm();
      this.form.parentId = row ? row.id : 0; // 确保新增的节点归属于当前父节点
      this.form.level = row ? (row.level + 1 <= 3 ? row.level + 1 : 3) : 1; // 设置默认层级
      this.open = true;
      this.title = row ? `添加子类目 - 父级: ${row.name}` : '添加根类目';
    },

    handleUpdate(row) {
      getTree(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改类目';
      });
    },

    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.name + '"的美团类目?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delTree(row.id);
      }).then(() => {
        this.$message.success('删除成功');
        this.getList();
      }).catch(error => {
        if (error !== 'cancel') { // 如果不是取消操作导致的错误，才显示错误信息
          this.$message.error('删除失败：' + error.message);
        }
      });
    },

    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const action = this.form.id ? updateTree : addTree;
          action(this.form).then(() => {
            this.$message.success(this.form.id ? '修改成功' : '新增成功');
            this.open = false;
            this.getList();
          });
        }
      });
    },

    cancel() {
      this.open = false;
    },

    resetForm() {
      this.form = { id: null, categoryId: '', name: '', parentId: null, level: null };
    },

    /** 处理配置按钮点击 */
    handleConfig(row) {
      this.configForm = {
        id: row.id,
        name: row.name,
        categoryId: row.categoryId,
        selectedAttributes: []
      };
      
      // 获取已配置的属性
      getAttribute(row.id).then(response => {
        if (response.data) {
          // 将后端返回的属性数据转换为下拉框需要的格式
          this.configForm.selectedAttributes = response.data.map(item => item.id);
        }
        this.configOpen = true;
      }).catch(error => {
        this.$message.error('获取配置失败：' + error.message);
        this.configOpen = true;
      });
    },
    
    /** 加载属性列表 */
    loadAttributes() {
      listAttribute().then(response => {
        // 处理属性列表数据
        this.attributeOptions = response.rows.map(attr => ({
          id: attr.id,
          name: attr.name,
          value: attr.id, // el-select需要的value字段
          label: attr.name // el-select需要的label字段
        }));
      });
    },
    
    /** 提交配置表单 */
    submitConfigForm() {
      const saveData = {
        categoryId: this.configForm.id,
        attributeIds: this.configForm.selectedAttributes
      };
      
      addAttribute(saveData).then(() => {
        this.$message.success('配置保存成功');
        this.configOpen = false;
      }).catch(error => {
        this.$message.error('配置保存失败：' + error.message);
      });
    },

    filterMethod(query, item) {
      // 实现过滤逻辑
      return item.label.includes(query);
    }
  }
};
</script>

<style scoped>
/* 变量定义 */
:root {
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --background-color: #f5f7fa;
  --text-color: #303133;
  --border-color: #DCDFE6;
}

/* 容器样式 */
.app-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.tree-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 头部样式 */
.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: linear-gradient(to right, #f7fbff, #f0f7ff);
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #3a5a97;
}

.header-title i {
  font-size: 20px;
  margin-right: 8px;
  color: #409EFF;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.add-btn {
  background: linear-gradient(135deg, #4776e6, #5a8aef);
  border: none;
  box-shadow: 0 2px 6px rgba(67, 118, 230, 0.2);
}

.toggle-btn {
  background: linear-gradient(135deg, #90a4ae, #b0bec5);
  border: none;
  box-shadow: 0 2px 6px rgba(144, 164, 174, 0.2);
}

/* 表格内容区域 */
.tree-content {
  padding: 20px;
}

.tree-table {
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #ebeef5;
}

/* 表格行样式 */
::v-deep .tree-row.level-1 {
  background-color: rgba(247, 250, 255, 0.6);
}

::v-deep .tree-row.level-2 {
  background-color: rgba(250, 252, 255, 0.4);
}

::v-deep .tree-row.level-3 {
  background-color: rgba(252, 254, 255, 0.2);
}

::v-deep .tree-row:hover > td {
  background-color: #f0f7ff !important;
}

/* ID单元格样式 */
.id-cell {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.id-badge {
  display: inline-block;
  padding: 2px 8px;
  background: #f5f7fa;
  color: #606266;
  border-radius: 12px;
  font-family: 'Courier New', monospace;
  font-weight: 600;
  border: 1px solid #e6effd;
}

/* 名称单元格样式 */
.name-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px 0;
}

.name-cell i {
  font-size: 18px;
  margin-right: 8px;
  color: #409EFF;
  background: rgba(64, 158, 255, 0.1);
  padding: 6px;
  border-radius: 4px;
}

.name-text {
  font-weight: 500;
  margin-right: 8px;
}

.level-tag {
  padding: 0 5px;
  height: 20px;
  line-height: 18px;
  font-size: 10px;
}

/* 父ID单元格样式 */
.parent-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.parent-icon {
  color: #67C23A;
  margin-right: 4px;
}

.parent-id {
  color: #606266;
  font-weight: 500;
}

.root-node {
  display: inline-block;
  padding: 2px 8px;
  background: rgba(103, 194, 58, 0.1);
  color: #67C23A;
  border-radius: 12px;
  font-size: 12px;
  border: 1px solid rgba(103, 194, 58, 0.2);
}

/* 层级单元格样式 */
.level-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px 0;
}

.level-cell .el-progress {
  width: 80%;
  margin-bottom: 5px;
}

.level-value {
  display: inline-block;
  width: 22px;
  height: 22px;
  line-height: 22px;
  border-radius: 50%;
  background: #f5f7fa;
  color: #606266;
  text-align: center;
  font-weight: 600;
  font-size: 12px;
  border: 1px solid #e6effd;
}

/* 属性单元格样式 */
.attr-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.attr-indicator {
  border-radius: 12px;
  padding: 7px 12px;
}

.no-attr {
  color: #909399;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.no-attr i {
  margin-right: 4px;
  font-size: 14px;
  color: #F56C6C;
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.op-btn {
  width: 32px;
  height: 32px;
  padding: 0;
  font-size: 14px;
  transition: all 0.3s;
}

.op-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 弹窗样式 */
::v-deep .tree-dialog .el-dialog__header,
::v-deep .config-dialog .el-dialog__header {
  background: linear-gradient(to right, #f7f9fc, #eef2f9);
  padding: 15px 20px;
  border-bottom: 1px solid #e8eaec;
}

::v-deep .tree-dialog .el-dialog__body,
::v-deep .config-dialog .el-dialog__body {
  padding: 25px;
}

.dialog-content,
.config-content {
  max-height: 60vh;
  overflow-y: auto;
}

.custom-input,
.custom-select,
.custom-number {
  width: 100%;
}

.parent-info,
.level-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.parent-info i,
.level-hint i {
  margin-right: 5px;
  color: #409EFF;
}

/* 配置弹窗样式 */
.config-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f7f9fc;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-label {
  width: 100px;
  color: #606266;
  display: flex;
  align-items: center;
}

.info-label i {
  margin-right: 5px;
  color: #409EFF;
}

.info-value {
  font-weight: 500;
  color: #303133;
}

.attribute-selector {
  width: 100%;
}

.attribute-option {
  display: flex;
  align-items: center;
}

.attribute-option i {
  margin-right: 5px;
  color: #409EFF;
}

.selected-count {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
}

.selected-count i {
  margin-right: 5px;
  color: #67C23A;
}

/* 对话框底部样式 */
::v-deep .dialog-footer {
  padding: 10px 20px 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .tree-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .operation-btns {
    flex-wrap: wrap;
  }
}
</style>
